import axios from 'axios'
import { Toast } from 'antd-mobile'
import { getRedirectPath } from '../utils/index'

const AUTH_SUCCESS = 'AUTH_SUCCESS'
const LOGOUT = 'LOGOUT'
const LOAD_DATA ='LOAD_DATA'
const ERROR_MSG = 'ERROR_MSG'

const initState = {
    redirectTo: '',
    msg: '',
    user: '',
    type: ''
}
export function user(state = initState, action) {
    switch(action.type) {
        case AUTH_SUCCESS: 
            return { ...state, msg: '', redirectTo: getRedirectPath(action.payload), ...action.payload }
        case LOAD_DATA:
            return { ...state, ...action.payload } 
        case LOGOUT:
            return { ...initState, redirectTo: '/login' }
        case ERROR_MSG: 
            return { ...state, msg: action.msg, isAuth: false }
        default:
            return state
    }
}

function errorMsg(msg) {
    Toast.info(msg, 1)
    return { msg, type: ERROR_MSG }
}

function authSucess(data) {
    return {
        type: AUTH_SUCCESS,
        payload: data
    }
}

export function logout() {
    return {
        type: LOGOUT
    }
}

export function loadData(userinfo) {
    return {
        type: LOAD_DATA,
        payload: userinfo
    }    
}

export function register(params) {
    return dispatch => {
        axios.post('/user/register', params)
        .then(res => {
            if (res.status === 200 && res.data.code === 0) {
                dispatch(authSucess(res.data.data))
            } else {
                dispatch(errorMsg(res.data.msg))
            }            
        })
    }
}

export function login(params) {
    return dispatch => {
        axios.post('/user/login', params)
            .then(res => {
                if (res.status === 200 && res.data.code === 0) {
                    dispatch(authSucess(res.data.data))
                } else {
                    dispatch(errorMsg(res.data.msg))
                }
            })
    }
}